<template>
  <view class="link-wifi">
    <div
      class="relative showMyBindWifi paddingTop-40 paddingRight-36"
      v-if="isShowMyBindWifi"
    >
      <div
        class="box absolute flex-align-center"
        @click="$Router.push({ name: 'myBindWifiList' })"
      >
        <div
          :style="{
            backgroundColor: themeColor,
            padding: '10rpx',
            borderRadius: '50%',
          }"
          class="marginRight-10"
        >
          <u-icon name="wifi" color="#fff" size="28rpx" />
        </div>
        <span :style="{ color: themeColor }" style="font-size: 28rpx"
          >我的WiFi</span
        >
      </div>
    </div>
    <div class="paddingTop-20">
      <view v-if="loading === WIFI_STATE.TESTING" class="container">
        <div class="flex-justify-content-center">
          <u-icon name="wifi" size="70rpx" :color="themeColor" />
        </div>
        <span>WiFi检测中</span>
      </view>

      <view v-if="loading === WIFI_STATE.LINKING" class="container">
        <div class="flex-justify-content-center">
          <round-dot :color="themeColor" />
          <!--          <u-loading-icon-->
          <!--            size="70rpx"-->
          <!--            color="#FFB72F"-->
          <!--            inactive-color="#FFB72F"-->
          <!--          />-->
        </div>
        <span>连接中，请稍等...</span>
      </view>

      <view v-if="loading === WIFI_STATE.SUCCESS" class="container">
        <div class="flex-justify-content-center">
          <u-icon name="checkmark-circle-fill" size="84rpx" color="green" />
        </div>
        <span>连接成功</span>
      </view>

      <view v-if="loading === WIFI_STATE.LINK_FAIL" class="container">
        <div class="flex-justify-content-center">
          <u-icon name="close-circle-fill" size="84rpx" color="red" />
        </div>
        <span>连接失败，请联系门店工作人员处理</span>
      </view>

      <view v-if="loading === WIFI_STATE.WIFI_FAIL" class="container">
        <div class="flex-justify-content-center">
          <u-icon name="warning-fill" size="84rpx" color="red" />
        </div>
        <span>WiFi打开失败，请检查手机WiFi设置</span>
      </view>
      <view
        v-if="loading === WIFI_STATE.LOCATION_ENABLED_FAIL"
        class="container"
      >
        <div class="flex-justify-content-center">
          <u-icon name="warning-fill" size="84rpx" color="red" />
        </div>
        <span>连接失败，请检查手机定位服务</span>
      </view>
      <view
        v-if="loading === WIFI_STATE.LOCATION_AUTHORIZED_FAIL"
        class="container"
      >
        <div class="flex-justify-content-center">
          <u-icon name="warning-fill" size="84rpx" color="red" />
        </div>
        <span>连接失败，微信定位权限未启用</span>
      </view>
    </div>
    <div class="advertisement marginTop-100 marginBottom-13">
      <div v-if="advertisement_1" class="advertisement_1">
        <image
          :src="advertisement_1.picUrl"
          @click="handleJumpAd(advertisement_1)"
        />
      </div>
    </div>
    <div class="couponList" v-if="app_token">
      <coupon-list />
    </div>
    <wi-fi-link-error-modal ref="WiFiLinkErrorModalRef" />
    <advertisement-success-modal ref="advertisementSuccessModalRef" />

    <error-modal ref="errorModalRef" />
  </view>
</template>

<script>
import { WIFI_STATE } from "@/pages/sp-store/const";
import WiFiLinkErrorModal from "../error-popup";
import advertisementSuccessModal from "../adertisement-success";
import roundDot from "../roundDot";
import couponList from "../coupon-list";
import {
  getAdvertByCurrentTime,
  myBindWifiList,
} from "@/service/api/sp-store/wifi";
import {
  EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI,
  EVENT_TRACK_TYPE_OF_BUSINESS_FOR_WIFI,
  WIFI_ERROR_CODE,
  WIFI_POSITION,
} from "@/pages/sp-store/const/wifi";
import jumpAdvertisement from "@/pages/sp-store/mixin/link-wifi/jumpAdvertisement";
import { mapState } from "vuex";
import handleEventTrack from "@/mixin/handleEventTrack";
import errorModal from "../../../../components/errorModal";

export default {
  mixins: [jumpAdvertisement, handleEventTrack],
  components: {
    WiFiLinkErrorModal,
    advertisementSuccessModal,
    couponList,
    roundDot,
    errorModal,
  },
  computed: {
    ...mapState("sp-common/auth", ["app_token"]),
    ...mapState("sp-common/base", ["themeColor"]),
    isHasLoadPage({ options }) {
      return !!options?.name;
    },
    eventTrackMustInfo({ options }) {
      return {
        sign: "wifi",
        opType: EVENT_TRACK_TYPE_OF_BUSINESS_FOR_WIFI.LINK,
        wifiName: options?.wifiName,
        wifiPassword: options?.password,
        pubDomainShopName: options?.pubDomainShopName,
        pubDomainShopId: options?.pubDomainShopId,
        pubDomainBusinessId: options?.pubDomainBusinessId,
        deviceNo: options?.wifiCode,
        phone: options?.phone,
        storeNo: options?.storeNo,
      };
    },
  },
  data() {
    return {
      loading: WIFI_STATE.TESTING,
      WIFI_STATE,
      deviceSystem: "",
      options: null,
      urlQuery: null,
      timer: null,
      setTimeoutTimer: null,
      advertisement_1: null,
      advertisement_success: null,
      isShowMyBindWifi: false,
      fetchAdvertisementDataNum: 0,
      failConnectNum: 0,
    };
  },
  created() {
    this.loading = WIFI_STATE.TESTING;
    uni.getSystemInfo({
      success: (res) => {
        this.deviceSystem = res.osName;
      },
    });
  },
  watch: {
    app_token: {
      handler(val) {
        if (val) {
          this.fetchMyWiFiList(); //请求我自己的WiFi绑定列表
          this.fetchAdvertisementData(); //请求广告
        }
      },
      deep: true,
      immediate: true,
    },
  },
  destroyed() {},
  onShow() {},
  methods: {
    handleReceive(options) {
      console.log("link-wifi初始化", options, this.loading);
      this.options = options;
      const loadingType = [
        WIFI_STATE.WAITING,
        WIFI_STATE.LINKING,
        // WIFI_STATE.SUCCESS,
        // WIFI_STATE.LINK_FAIL,
      ];
      if (loadingType.includes(this.loading)) return; //当前连接状态上述状态的时候,不进行下去,因为还处在流程当中
      const systemInfo = uni.getSystemInfoSync();
      // console.log("当前状态", this.loading);
      if (!systemInfo?.wifiEnabled) {
        this.handleEventTrack({
          ...this.options,
          ...this.eventTrackMustInfo,
          status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
          failReason: "初始化WiFi开始，用户未打开手机WiFi",
        }); //数据埋点
        this.loading = WIFI_STATE.WIFI_FAIL;
        uni.showToast({
          icon: "none",
          title: "请打开手机WiFi",
        });
        return;
      } else if (!systemInfo?.locationEnabled) {
        this.loading = WIFI_STATE.LOCATION_ENABLED_FAIL;
        this.$refs.errorModalRef.open("请先打开手机定位服务");
        this.handleEventTrack({
          ...this.options,
          ...this.eventTrackMustInfo,
          status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
          failReason: "初始化WiFi开始，用户未打开手机定位服务",
        }); //数据埋点
        return;
      } else if (!systemInfo?.locationAuthorized) {
        this.loading = WIFI_STATE.LOCATION_AUTHORIZED_FAIL;
        this.$refs.errorModalRef.open(
          "微信定位权限未启用，请前往系统设置页面启用微信定位权限"
        );
        this.handleEventTrack({
          ...this.options,
          ...this.eventTrackMustInfo,
          status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
          failReason: "初始化WiFi开始，用户微信定位权限未启用",
        }); //数据埋点
        return;
      }
      this.loading = WIFI_STATE.TESTING;
      // WiFi码牌直连
      this.$nextTick(() => {
        this.connectWifi();
      });
    },
    async fetchMyWiFiList() {
      const res = await myBindWifiList();
      if (res?.length > 0) {
        this.isShowMyBindWifi = true;
      }
    },
    connectWifi() {
      this.loading = WIFI_STATE.LINKING;
      this.handleCheckWiFiHasLinked().catch(() => {
        const options = this.options;
        uni.stopPullDownRefresh();
        uni.startWifi({
          success: (res) => {
            this.handleEventTrack({
              ...res,
              ...this.options,
              ...this.eventTrackMustInfo,
              status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_SUCCESS,
              failReason:
                "初始化WiFi成功，连接WiFi开始" +
                `，此时重连次数：${this.failConnectNum}次`,
            }); //数据埋点
            console.log("startWifi成功", res);
            uni.connectWifi({
              SSID: options.name,
              password: options.password,
              maunal: false,
              forceNewApi: false,
              success: (res) => {
                console.log("connectWifi成功");
                this.$nextTick(() => {
                  this.handleEventTrack({
                    ...res,
                    ...this.options,
                    ...this.eventTrackMustInfo,
                    status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_SUCCESS,
                    failReason:
                      "连接WiFi成功" +
                      `，此时重连次数：${this.failConnectNum}次`,
                  }); //数据埋点
                  this.failConnectNum = 0;
                });
                this.listenConnectWifi();
              },
              fail: (err) => {
                console.log("connectWifi-err", err, options);
                const once = [12002, 12008, 12014];
                if (once.includes(err.errCode)) {
                  this.$nextTick(() => {
                    this.handleEventTrack({
                      ...res,
                      ...this.options,
                      ...this.eventTrackMustInfo,
                      status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
                      failReason: "连接WiFi失败" + JSON.stringify(err),
                    }); //数据埋点
                    this.$refs.errorModalRef.open(
                      "WiFi密码错误，或当前WiFi不在可连接范围内，请联系门店工作人员处理"
                    );
                    this.failConnectNum = 0;
                    this.loading = WIFI_STATE.LINK_FAIL;
                  });
                } else {
                  this.handleReConnectWifi(err);
                }
              },
            });
          },
          fail: (err) => {
            this.loading = WIFI_STATE.WIFI_FAIL;
            console.log("connectWifiFun-startWifi err", err);
            this.handleEventTrack({
              ...err,
              ...this.options,
              ...this.eventTrackMustInfo,
              status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
              failReason: "初始化WiFi失败，" + JSON.stringify(err),
            }); //数据埋点
          },
        });
      });
    },
    handleLinkFail() {
      const options = this.options;
      this.loading = WIFI_STATE.LINK_FAIL;
      //场景补充，WiFi首次连接失败以后
      this.$refs.WiFiLinkErrorModalRef.open({
        ssid: options.name,
        password: options.password,
      });
      // console.log("handleLinkFail-err", this.loading, options);
    },
    //场景：连接错误以后，输入密码正确，发现已经连接，即是联网成功
    handleCheckWiFiHasLinked() {
      return new Promise((resolve, reject) => {
        uni.stopPullDownRefresh();
        uni.startWifi({
          success: () => {
            uni.getConnectedWifi({
              success: (res) => {
                console.log(
                  "连接错误以后，输入密码正确，发现已经连接，即是联网成功",
                  res
                );
                if (
                  res?.wifi?.SSID === this.options?.name
                  // &&res?.wifi?.signalStrength > 0
                ) {
                  this.handleEventTrack({
                    ...res,
                    ...this.options,
                    ...this.eventTrackMustInfo,
                    status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_SUCCESS,
                    failReason:
                      "监听本手机WiFi，发现本手机WiFi与码牌WiFi一致，连接成功，",
                  }); //数据埋点
                  this.$refs.WiFiLinkErrorModalRef.close();
                  this.$nextTick(() => {
                    this.loading = WIFI_STATE.SUCCESS;
                    this.handleReOpenSuccessModalRef();
                  });
                  resolve();
                  clearInterval(this.timer);
                  this.timer = null;
                } else {
                  reject();
                }
              },
              fail: () => {
                reject();
              },
            });
          },
          fail: (err) => {
            console.log("handleCheckWiFiHasLinkedFun-err", err);
            this.handleEventTrack({
              ...err,
              ...this.options,
              ...this.eventTrackMustInfo,
              status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
              failReason: "初始化WiFi失败，" + JSON.stringify(err),
            }); //数据埋点
            this.loading = WIFI_STATE.WIFI_FAIL;
            // this.loading = WIFI_STATE.WIFI_FAIL;
            if (err?.errCode) {
              this.$refs.errorModalRef.open(
                err?.errCode ? WIFI_ERROR_CODE[err?.errCode] : "请打开手机WiFi"
              );
            } else {
              uni.showToast({
                icon: "none",
                title: "请打开手机WiFi",
              });
            }
          },
        });
      });
    },
    listenConnectWifi() {
      console.log("手机连接成功WiFi的场景");
      this.timer = setInterval(() => {
        uni.getConnectedWifi({
          success: (res) => {
            console.log("=监听已连接的WiFi", res);
            if (res?.wifi?.SSID === this.options?.name) {
              this.loading = WIFI_STATE.SUCCESS;
              this.handleReOpenSuccessModalRef();
              clearInterval(this.timer);
              this.timer = null;
            }
          },
        });
      }, 500);
    },
    handleReOpenSuccessModalRef() {
      if (this.advertisement_success) {
        if (this.$refs?.advertisementSuccessModalRef) {
          this.$refs?.advertisementSuccessModalRef?.open(
            this.advertisement_success
          );
        } else {
          setTimeout(() => {
            this.handleReOpenSuccessModalRef();
          }, 500);
        }
      } else {
        setTimeout(() => {
          this.handleReOpenSuccessModalRef();
        }, 500);
      }
    },
    handleReConnectWifi(err) {
      //兼容失败后手机自动连接WiFi的场景
      if (this.failConnectNum >= 1) {
        this.$nextTick(() => {
          this.handleEventTrack({
            ...err,
            ...this.options,
            ...this.eventTrackMustInfo,
            status: EVENT_TRACK_EVENT_OF_RESULT_FOR_WIFI.WECHAT_FAIL,
            failReason:
              "连接WiFi失败" +
              `，此时重连次数：${
                this.failConnectNum
              }次，原因是：${JSON.stringify(err)}`,
          }); //数据埋点
          this.failConnectNum = 0;
          this.handleLinkFail();
        });
        return;
      }
      console.log("兼容失败后手机自动连接WiFi的场景", err);
      this.failConnectNum += 1;
      this.connectWifi();
    },
    async fetchAdvertisementData() {
      this.fetchAdvertisementDataNum += 1;
      try {
        const data = await getAdvertByCurrentTime({ status: 1 });
        if (data) {
          data.map((d) => {
            if (d.innerPageJson) {
              d.innerPageJson = JSON.parse(d.innerPageJson);
            }
          });
          this.advertisement_1 =
            data.filter((d) => d?.no === WIFI_POSITION.POSITION_1)[0] || null;
          this.advertisement_success =
            data.filter((d) => d?.no === WIFI_POSITION.POSITION_SUCCESS)[0] ||
            null;
        }
      } catch (err) {
        console.log("获取广告失败");
        setTimeout(() => {
          if (this.fetchAdvertisementDataNum >= 10) return;
          this.fetchAdvertisementData();
        }, 1000);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.link-wifi {
  min-height: 100vh;
  background-color: #f7f7f7;
}
.container {
  width: calc(100vw - 40 * 2rpx);
  padding: 20rpx 40rpx;
  height: 138rpx;
  background-color: #f7f7f7;
  text-align: center;
  .flex-justify-content-center {
    margin-bottom: 33rpx;
  }
  span {
    color: #131313;
    opacity: 0.8;
  }
}
.showMyBindWifi {
  height: 80rpx;
  .box {
    right: 20rpx;
  }
}

.advertisement_1 {
  width: 710rpx;
  height: 200rpx;
  margin: 0 auto;
  image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
  }
}
.couponList {
  background-color: #f7f7f7;
}
.business-container {
  padding: 0 53rpx;
  text-align: left;
  .font-red {
    color: red;
  }
  .text {
    margin: 21rpx 0;
    text-align: left;
    font-size: 26rpx;
  }
  .fail {
    font-size: 29rpx;
  }
}
</style>
